package com.uxsino.simo.indicator;

import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.uxsino.commons.utils.config.ConfigProp;
import com.uxsino.reactorq.model.FieldType;
import com.uxsino.reactorq.model.INDICATOR_TYPE;
import com.uxsino.simo.networkentity.EntityInfo;
import com.uxsino.simo.query.QueryContext;

public class CompoundIndicator extends Indicator implements ICompound {

    @JsonProperty("fields")
    @JSONField(name = "fields")
    protected Map<String, IIndicatorField> fields;

    private String keyFieldNames;

    @ConfigProp(name = "extend_fields")
    boolean fieldExtendable = false;

    public CompoundIndicator(String indicatorName) {
        super(indicatorName);
        fields = new LinkedHashMap<String, IIndicatorField>();
    }

    @Override
    @JsonProperty("type")
    @JSONField(name = "type")
    public INDICATOR_TYPE getIndicatorType() {
        return INDICATOR_TYPE.COMPOUND;
    }

    public void addField(String fieldName, IIndicatorField field) {
        fields.put(fieldName, field);
    }

    @JsonIgnore
    @JSONField(serialize = false)
    @Override
    public Iterator<Map.Entry<String, IIndicatorField>> getFieldIterator() {
        return fields.entrySet().iterator();
    }

    @Override
    @JsonIgnore
    @JSONField(serialize = false)
    public int getFieldsCount() {
        return fields.size();
    }

    @Override
    public IIndicatorField getField(String fieldName) {
        return fields.get(fieldName);
    }

    @Override
    public String[] getKeyFieldNames() {
        return null == keyFieldNames ? new String[0] : keyFieldNames.split(",");
    }

    @Override
    @JsonIgnore
    @JSONField(serialize = false)
    public Collection<IIndicatorField> getFieldsCollection() {
        return fields.values();
    }

    @Override
    public IIndicatorField createField(String name, FieldType fieldType) {
        return new IndicatorField(name, fieldType);
    }

    @Override
    public void setKeyFieldNames(String names) {
        keyFieldNames = names;
    }

    @Override
    public void doPostQuery(EntityInfo entity, QueryContext ctxt, Object value) {
        @SuppressWarnings("unchecked")
        Map<String, Object> mv = (Map<String, Object>) value;

        if (mv == null) {
            return;
        }

        // fill fields not retracted with null
        for (String fieldName : fields.keySet()) {
            mv.putIfAbsent(fieldName, null);
        }
    }

    @Override
    public boolean isFieldsExtendable() {
        return fieldExtendable;
    }
}
